<template>
	<div class="company-list">
		<list-title :data="header"></list-title>
		<div class="search">
			<el-form :inline="true" :model="searchForm" class="demo-form-inline">
				<el-form-item label="客户名称">
					<el-input v-model="searchForm.company_name" placeholder="客户名称"></el-input>
				</el-form-item>
				<el-form-item label="地区">
					<el-select v-model="checkProvince" placeholder="省" @change="getCityByProvince('')">
						<el-option v-for="(item, index) in provinceList" :key="index" :label="item.areaname" :value="item.id"></el-option>
					</el-select>
					<el-select v-model="checkCity" placeholder="市">
						<el-option v-for="(item, index) in cityList" :key="index" :label="item.areaname" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="searchForm.state" placeholder="状态">
						<el-option label="启用" value="1"></el-option>
						<el-option label="等待审核" value="2"></el-option>
						<el-option label="审核不通过" value="3"></el-option>
						<el-option label="注销" value="4"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="添加时间">
					<el-date-picker
					v-model="searchForm.regTime"
					type="daterange"
					format="yyyy-MM-dd"
					value-format="yyyy-MM-dd"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="mini" @click="searchSubmit">查询</el-button>
				</el-form-item>
			</el-form>
		</div>
		<list-table :list="companyList" :tableLoading="tableLoading" :footer="true" :pagination="pagination">
			<template v-slot:data>
				<el-table-column prop="companyInfo" label="客户名称">
					<template slot-scope="scope">
						<div>{{ scope.row.companyName + "（" + scope.row.level + "级）" }}</div>
						<div v-html="scope.row.companyProfile"></div>
					</template>
				</el-table-column>
				<el-table-column prop="companyInfo" label="账户">
					<template slot-scope="scope">
						<div :class="scope.row.account == '0.00'?'danger':''">{{ scope.row.account }}</div>
					</template>
				</el-table-column>
				<el-table-column prop="province" label="区域地址">
					<template slot-scope="scope">
						<span v-html="scope.row.province + '/' + scope.row.city"></span>
					</template>
				</el-table-column>
				<el-table-column prop="comid" label="COMID" show-overflow-tooltip></el-table-column>
				<el-table-column prop="contactsInfo" label="联系人信息">
					<template slot-scope="scope">
						<div v-for="(item, index) in scope.row.contacts" :key="index" v-html="scope.row.contacts[index] + '/' + scope.row.phones[index]"></div>
					</template>
				</el-table-column>
				<!-- <el-table-column prop="state" label="当前状态"></el-table-column> -->
				<el-table-column prop="state" label="当前状态" width="120px">
					<template slot-scope="scope">
						<el-select v-model="scope.row.state" placeholder="请选择" :class="'state' + scope.row.state" @change="stateChange($event, scope.row, scope.$index)" :disabled="stateLock[scope.$index+1]">
							<el-option label="启用" value="1"></el-option>
							<el-option label="等待审核" value="2"></el-option>
							<el-option label="审核不通过" value="3"></el-option>
							<el-option label="注销" value="4"></el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column prop="addTime" label="添加时间"></el-table-column>
				<el-table-column label="操作" width="200">
					<template slot-scope="scope">
						<el-button type='text' size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type='text' size="mini" @click="openInitpwd(scope.row.comid, scope.row.companyName)">初始化密码</el-button>
						<el-button type='text' size="mini" @click="openTopup(scope.row.comid, scope.row.companyName)">充值</el-button>
					</template>
				</el-table-column>
			</template>
		</list-table>
		<!-- 初始化密码 开始 -->
		<el-dialog :title="dialogPwd.title" :visible.sync="dialogPwd.visible" :close-on-click-modal="false" width="460px">
			<el-form :model="initPwdForm" :rules="initPwdRules" ref="initPwdForm" label-width="100px">
				<div style="margin: 0 28px; line-height: 50px;">
					<span>企业名称：</span>
					<span>{{ initPwdForm.data.companyname }}</span>
				</div>
				<el-form-item label="新密码" prop="data.password" style="width: 378px;">
					<el-input type="password" v-model="initPwdForm.data.password" placeholder="新密码"></el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="data.passwordConfirm" style="width: 378px;">
					<el-input type="password" v-model="initPwdForm.data.passwordConfirm" placeholder="确认密码"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogPwd.visible = false">取 消</el-button>
				<el-button type="primary" @click="submitInitPwdForm('initPwdForm')" :disabled='initPwdForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='initPwdForm.submitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 初始化密码 结束 -->
		<!-- 充值 开始 -->
		<el-dialog :title="dialogTopup.title" :visible.sync="dialogTopup.visible" :close-on-click-modal="false" width="460px">
			<el-form :model="topUpForm" :rules="topUpRules" ref="topUpForm" label-width="150px">
				<div style="margin-left: 70px; line-height: 50px;">
					<span>企业名称：</span>
					<span style="margin-left: 5px">{{ topUpForm.data.companyname }}</span>
				</div>
				<el-form-item label="充值金额（元）" prop="data.amount" style="width: 378px;">
					<el-input-number v-model="topUpForm.data.amount" :min="0" step-strictly style="width: 150px;"></el-input-number>
				</el-form-item>
				<el-form-item label="备注" prop="data.remark" style="width: 378px;">
					<el-input type="textarea" :rows="5" maxlength="256" show-word-limit placeholder="请输入备注" v-model="topUpForm.data.remark"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogTopup.visible = false">取 消</el-button>
				<el-button type="primary" @click="submitTopUpForm('topUpForm')" :disabled='topUpForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='topUpForm.submitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 充值 结束 -->
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import ListTable from "pc/common/ListTable"
import {filterEmpty, getNavbarByMenuList, judgeAuth} from "static/js/common.js"
import {SEC_NAVBAR_COMPANY} from '@/config/backArgs.js'
import {mapMutations} from 'vuex'
import {mapGetters} from 'vuex'
export default {
	inject: ['reload'],
	data() {
		var validatePass = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入密码'));
			} else {
				if (this.initPwdForm.data.password !== '') {
					this.$refs.initPwdForm.validateField('password');
				}
				callback();
			}
		};
		var validatePass2 = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'));
			} else if (value !== this.initPwdForm.data.password) {
				callback(new Error('两次输入密码不一致!'));
			} else {
				callback();
			}
		};
		var validateNumSize = (rule, value, callback) => {
			console.log(value)
			if (value === '') {
				callback(new Error('请输入金额'));
			} else {
				if (value <= 0) {
					callback(new Error('金额比较大于0'));
				}
				callback();
			}
		};
		return {
			/*头部数据*/
			header: {
				title: '客户列表',
				reload: true,
				buttons: [
					{
						title: '添加客户',
						type: 'primary',
						pathName: 'pc/companycenter/company/Company',
						auth: false,
					}
				]
			},
			/*初始化密码 弹窗*/
			dialogPwd: {
				'title': '初始化密码',
				'visible': false
			},
			/*充值 弹窗*/
			dialogTopup: {
				'title': '充值',
				'visible': false
			},
			/*搜索*/
			searchForm: {
				company_name: this.$route.query.company_name,
				province: this.$route.query.province,
				city: this.$route.query.city,
				state: this.$route.query.state,
				regTime: (this.$route.query.begin_time!=undefined)?[this.$route.query.begin_time, this.$route.query.end_time]:'',
				// regTime: '',
			},
			provinceList: [],//省份
			cityList: [],//省份
			companyList: [
				// {
				// 	id: 1,
				// 	companyName: '昊视科技',
				// 	companyProfile: '营业执照',
				// 	province: '省',
				// 	city: '市',
				// 	comid: '00000000',
				// 	contacts: '高见',
				// 	phones: '13915028703',
				// 	account: 0,
				// 	level: 10,
				// 	state: 2,
				// 	addTime: '2019-09-09 08:08:08',
				// },
			],
			stateLock: [],
			pagination: {
				count: 0,
				currPage: 1,
				pageSize: 3
			},
			tableLoading: true,
			/*初始化密码 表单*/
			initPwdForm: {
				submitLock: false,
				auth: false,//权限
				data: {
					companyname: '',
					comid: '',
					password: '',
					passwordConfirm: ''
				}
			},
			initPwdRules: {
				data: {
					password: [
						{ validator: validatePass, trigger: 'blur' }
					],
					passwordConfirm: [
						{ validator: validatePass2, trigger: 'blur' }
					],
				}
			},
			/*充值 表单*/
			topUpForm: {
				submitLock: false,
				auth: false,//权限
				data: {
					companyname: '',
					comid: '',
					amount: 0,
					remark: ''
				}
			},
			topUpRules: {
				data: {
					amount: [
						{ required: true, message: '请输入金额', trigger: 'blur' },
						{ type: 'number', message: '金额必须为数字'},
						{ validator: validateNumSize, trigger: 'blur' }
					]
				}
			}
		};
	},
	components: {
		ListTitle,
		ListTable,
	},
	created: function() {
		/*获取所有客户数据*/
		this.getCompanyList()
		/*获取所有省份数据*/
		this.getProvinceList()
		if(this.$route.query.province != undefined){
			/*如果搜搜栏有市数据，则获取市数据*/
			this.getCityByProvince(this.$route.query.city)
		}
		/*权限判断显示*/
		this.header.buttons[0].auth = (judgeAuth('addCompany', this.allMenuList) == undefined)?false:true
	},
	watch: {
		/*监听路由变化，根据参数查询数据*/
		'$route' (to){
			this.tableLoading = true
			this.getCompanyList()
			/*点击navbar的时候，路由产生变化*/
			this.searchForm.company_name = this.$route.query.company_name
			this.searchForm.province = this.$route.query.province
			this.searchForm.city = this.$route.query.city
			this.searchForm.state = this.$route.query.state
			this.searchForm.regTime = (this.$route.query.begin_time!=undefined)?[this.$route.query.begin_time, this.$route.query.end_time]:''
		}
	},
	methods: {
		/*获取客户列表*/
		getCompanyList: function(){
			// this.$baseURL('http://super.ac.comdd')
			this.$get(this.$api.companyCenterList, this.$route.query).then(res => {
				// console.log(res);
				if(res.data.code == 10007){//后台提示需要登录
					this.$cookie.remove('isLogin');//刪除cookie登录信息
					this.reload();
				}
				if(res.data.code === 0){
					if(res.data.data.list != undefined){
						this.companyList = []
						Object.keys(res.data.data.list).forEach((k) => {
							/*
							注释原因： 343行 下面直接取的res.data.data.list[k].state 不需要转了
										之前是直接展示，现在需要直接修改状态
							*/
							// let state = '启用';
							// switch(res.data.data.list[k].state){
							// 	case '2':
							// 		state = '等待审核';
							// 		break;
							// 	case '3':
							// 		state = '审核不通过';
							// 		break;
							// 	case '4':
							// 		state = '已注销';
							// 		break;
							// }
							this.companyList.push ({
								id: res.data.data.list[k].com_id,
								companyName: res.data.data.list[k].company_name,
								companyProfile: res.data.data.list[k].business_license,
								province: (res.data.data.list[k].province != null)?res.data.data.list[k].province.areaname:"",
								city: (res.data.data.list[k].city != null)?res.data.data.list[k].city.areaname:"",
								comid: res.data.data.list[k].comid,
								contacts: res.data.data.list[k].contacts.split(','),
								phones: res.data.data.list[k].phones.split(','),
								account: res.data.data.list[k].account,
								level: res.data.data.list[k].level,
								state: res.data.data.list[k].state,
								addTime: res.data.data.list[k].add_time
							});
						})
						this.pagination = res.data.data.pageInfo
					}
					this.tableLoading = false
				}
			})
			.catch(err => {})
			.finally(() => {}) 
		},
		/*编辑客户*/
		handleEdit(index, row) {
			// console.log(row.id);
			this.$router.push({ name: 'pc/companycenter/company/Company', query: {id: row.comid}})
		},
		/*获取所有省份数据*/
		getProvinceList: function(){
			this.$get(this.$api.provinceList).then(res => {
				// console.log(res);
				if(res.data.code === 0){
					if(res.data.data != undefined){
						this.provinceList = res.data.data
					}
				}
			})
			.catch(err => {})
			.finally(() => {})
		},
		/*根据省份ID获取城市数据*/
		getCityByProvince: function(city){
			if(city == ''){
				this.searchForm.city = ''//清空已经选择的城市数据
			}else{
				this.searchForm.city = city//刷新页面的时候，有可能会出现有默认城市的情况
			}
			this.cityList = []//清空所有的城市，因为需要更新数据
			if(this.searchForm.province != ''){
				this.$get(this.$api.cityList, {
					'id': this.searchForm.province
				}).then(res => {
					// console.log(res);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.cityList = res.data.data
						}
					}
				})
				.catch(err => {})
				.finally(() => {})
			}
		},
		/*搜索提交*/
		searchSubmit: function(){
			let query = filterEmpty(JSON.parse(JSON.stringify(this.searchForm)))
			if(query.regTime != undefined){
				query = Object.assign({begin_time: query['regTime'][0], end_time: query['regTime'][1]}, query)
				delete query['regTime']
			}
			this.$router.push({query})
		},
		...mapMutations({
			setNavbar: 'setNavbar'
		}),
		/*
		初始化密码 弹窗
		comid 		
		*/
		openInitpwd: function(comid, companyname){
			if(this.$api.topUp != undefined){
				// console.log(comid)
				this.initPwdForm.data.comid = comid
				this.initPwdForm.data.companyname = companyname
				this.dialogPwd.visible = !this.dialogPwd.visible
			}
		},
		/*
		充值 弹窗
		comid 		
		*/
		openTopup: function(comid, companyname){
			if(this.$api.topUp != undefined){
				// console.log(comid)
				this.topUpForm.data.comid = comid
				this.topUpForm.data.companyname = companyname
				this.topUpForm.data.amount = 0
				this.dialogTopup.visible = !this.dialogTopup.visible
			}
		},
		/*初始化密码 提交表单*/
		submitInitPwdForm(formName) {
			if(!this.initPwdForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.initPwdForm.submitLock = true;
						/*初始化密码*/
						this.$post(this.$api.initPwd, {
							Admin: this.initPwdForm.data
						}).then(res => {
							// console.log(res);
							/*成功*/
							if(res.data.code == 0){
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'success'
								});
								this.$refs[formName].resetFields();
							}else{
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'error'
								});
							}
							this.initPwdForm.submitLock = false;
							this.dialogPwd.visible = !this.dialogPwd.visible
						});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*充值 提交表单*/
		submitTopUpForm(formName) {
			if(!this.topUpForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.topUpForm.submitLock = true;
						/*充值*/
						this.$post(this.$api.topUp, {
							CompanyAccountRecord: this.topUpForm.data
						}).then(res => {
							console.log(res);
							/*成功*/
							if(res.data.code == 0){
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'success'
								});
								this.$refs[formName].resetFields();
							}else{
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'error'
								});
							}
							this.topUpForm.submitLock = false;
							this.dialogTopup.visible = !this.dialogTopup.visible
						});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*重置表单*/
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
		/*单个改变状态*/
		stateChange(flag, row, index) {
			// console.log(row.id)
			/*请求后台*/
			// this.$baseURL(domain.ac)
			this.stateLock[index+1] = true//锁住当前的
			this.$post(this.$api.modifyCompany, {
				Company: {
					comid: row.comid,
					company_name: row.companyName,
					state: row.state
				}
			}).then(res => {
				if(res.data.code == 0){
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'success'
					});
				}else{
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'error'
					});
				}
				this.stateLock = []
				this.stateLock[index+1] = false//释放当前的
			})
			.catch(err => {})
			.finally(() => {}) 
		}
	},
	computed: {
		/*验证省份是否已经获取到，有了数据才展示,防止直接出现数字，比较尴尬*/
		checkProvince: {
			get: function () {
				if(this.provinceList.length > 0){
					return this.searchForm.province
				}else{
					return ''
				}
			},
			set: function (val) {
				this.searchForm.province = val
			}
		},
		/*验证城市是否已经获取到，有了数据才展示,防止直接出现数字，比较尴尬*/
		checkCity: {
			get: function () {
				if(this.cityList.length > 0){
					return this.searchForm.city
				}else{
					return ''
				}
			},
			set: function (val) {
				this.searchForm.city = val
			}
		},
		...mapGetters([
			'allMenuList'
		])
	}
};
</script>

<style lang="stylus" scoped>
.company-list
	.search
		margin-top: 10px
		.el-form-item--small.el-form-item
			margin-bottom: 0px
.state1
	border: 1px solid limegreen
.state2
	border: 1px solid orange
.state3
	border: 1px solid gray
.state4
	border: 1px solid red
.danger
	color: red
	font-weight: bold
.gold
	color: #ffd700
	font-weight: bold
</style>